<template>
  <div>
    <el-card class="box-card" style="margin-bottom:10px;position:relative;">
      <div slot="header" class="clearfix">
        <span>网站列表</span>
        <el-button style="float: right;" size="mini" @click="actionRefresh">刷新</el-button>
        <el-button style="float: right;margin-right:10px;" size="mini" @click="actionEditorOpen">新建</el-button>
      </div>
      
      <el-table :data="list" style="width: 100%">
        <el-table-column label="状态" width="50">
          <template slot-scope="scope">
            <span v-if="scope.row.isEnabled">启用</span>
          </template>
        </el-table-column>
        <el-table-column prop="serverName" label="网站" width="200"></el-table-column>
        <el-table-column align="right">
          <template slot-scope="scope">
            <el-dropdown v-if="null != scope.row.website" style="margin: 0 10px;" @command="actionShowLog">
              <el-button size="mini">日志<i class="el-icon-arrow-down el-icon--right"></i></el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-for="(logEntry, logEntryIndex) in scope.row.website.logs" 
                  :key="logEntryIndex" 
                  :command="logEntry.file"
                >{{logEntry.name}}</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <el-dropdown trigger="click" @command="actionHandleWebsiteOperationCommand">
              <el-button size="mini">
                操作 <i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-if="!scope.row.isEnabled" :command="{action:'Enable',site:scope.row.serverName,index:scope.$index}">启用</el-dropdown-item>
                <el-dropdown-item v-if="scope.row.isEnabled" :command="{action:'Disable',site:scope.row.serverName,index:scope.$index}">禁用</el-dropdown-item>
                <el-dropdown-item :command="{action:'Update',site:scope.row.serverName,index:scope.$index}">更新</el-dropdown-item>
                <el-dropdown-item :command="{action:'Rollback',site:scope.row.serverName,index:scope.$index}">回滚</el-dropdown-item>
                <el-dropdown-item :command="{action:'VirtualHostConfig',site:scope.row.serverName,index:scope.$index}">站点配置</el-dropdown-item>
                <el-dropdown-item :command="{action:'ManagementConfig',site:scope.row.serverName,index:scope.$index}">管理配置</el-dropdown-item>
                <el-dropdown-item :command="{action:'Delete',site:scope.row.serverName,index:scope.$index}">删除</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <dialog-virtual-host-config ref="dialogVirtualHostConfig" v-on:update="actionRefresh"></dialog-virtual-host-config>
    <dialog-virtual-host-edit ref="dialogVirtualHostEdit" v-on:update="actionRefresh"></dialog-virtual-host-edit>
    <dialog-log-viewer ref="dialogLogViewer"></dialog-log-viewer>
    <dialog-virtual-host-deploy ref="dialogDeploy"></dialog-virtual-host-deploy>
    <dialog-virtual-host-management-config ref="dialogManagementConfig"></dialog-virtual-host-management-config>
  </div>
</template>
<script>
import Common from '../../utils/Common.js'
import DialogLogViewer from '../DialogLogViewer.vue'
import DialogVirtualHostEdit from './DialogVirtualHostEdit.vue'
import DialogVirtualHostConfig from './DialogVirtualHostConfig.vue'
import DialogVirtualHostDeploy from './DialogVirtualHostDeploy.vue'
import DialogVirtualHostManagementConfig from './DialogVirtualHostManagementConfig.vue'
import yaml from 'js-yaml'
export default {
    name : 'ApacheVirtualHostList',
    components : {
        'dialog-virtual-host-config' : DialogVirtualHostConfig,
        'dialog-virtual-host-edit' : DialogVirtualHostEdit,
        'dialog-log-viewer' : DialogLogViewer,
        'dialog-virtual-host-deploy' : DialogVirtualHostDeploy,
        'dialog-virtual-host-management-config' : DialogVirtualHostManagementConfig,
    },
    data() {
        return {
            list : [],
        };
    },
    async mounted() {
        await this.actionRefresh();
    },
    methods : {
        /** 刷新 */
        async actionRefresh() {
            let server = this.$store.getters.serverCurrent;
            let cmd = await server.getCommander();
            let enSites = await cmd.ls('/etc/apache2/sites-enabled');
            for ( let i=0; i<enSites.length; i++ ) {
                enSites[i] = enSites[i].name;
            }

            let files = await cmd.ls('/etc/apache2/sites-available');
            let list = [];
            for ( let i=0; i<files.length; i++ ) {
                let vhost = {};
                vhost.serverName = files[i].name.substr(0, files[i].name.length-5);
                vhost.isEnabled = -1 != enSites.indexOf(files[i].name);
                vhost.file = files[i].name;
                
                vhost.website = null;
                let localConfigPath = server.localGetPath(`/websites/${vhost.serverName}.json`);
                if ( await Common.isFileExists(localConfigPath) ) {
                    let config = await Common.fileGetContent(localConfigPath);
                    vhost.website = JSON.parse(config);
                }

                list.push(vhost);
            }
            this.list = list;
        },

        /** 打开编辑弹框 */
        actionEditorOpen() {
            this.$refs.dialogVirtualHostEdit.open();
        },

        /** 查看日志 */
        actionShowLog( filepath ) {
            if ( undefined == filepath ) {
                this.$message.error('日志不存在');
                return;
            }

            this.$refs.dialogLogViewer.open(filepath);
        },

        // 执行网站操作
        actionHandleWebsiteOperationCommand( cmd ) {
            let handler = `handleWebsiteOperation${cmd.action}`;
            this[handler](cmd);
        },

        // 网站站点配置
        handleWebsiteOperationVirtualHostConfig( cmd ) {
            let vhost = this.list[cmd.index];
            this.$refs.dialogVirtualHostConfig.open(vhost);
        },

        // 网站管理配置
        handleWebsiteOperationManagementConfig( cmd ) {
            console.log(cmd.site);
            this.$refs.dialogManagementConfig.open(cmd.site);
        },

        // 站点更新
        handleWebsiteOperationUpdate( cmd ) {
            this.$refs.dialogDeploy.open(cmd.site, 'update');
        },

        // 站点更新
        handleWebsiteOperationRollback( cmd ) {
            this.$refs.dialogDeploy.open(cmd.site, 'rollback');
        },

        // 站点删除
        async handleWebsiteOperationDelete( cmd ) {
            try {
                await this.$confirm(`此操作将永久删除 ${cmd.site} 站点, 是否继续?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                });
            } catch {
                return;
            }
            
            let vhost = this.list[cmd.index];
            let server = this.$store.getters.serverCurrent;
            await server.exec(`a2dissite ${vhost.file}`);
            await server.exec('systemctl restart apache2');
            await server.exec(`rm -f /etc/apache2/sites-available/${vhost.file}`);
            await this.actionRefresh();
        },

        /** 启用站点 */
        async handleWebsiteOperationEnable( cmd ) {
            try {
                await this.$confirm(`此操作将启用 ${cmd.site} 站点, 是否继续?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                });
            } catch {
                return;
            }

            let vhost = this.list[cmd.index];
            let server = this.$store.getters.serverCurrent;
            await server.exec(`a2ensite ${vhost.file}`);
            await server.exec('systemctl restart apache2');
            await this.actionRefresh();
        },

        /** 禁用站点 */
        async handleWebsiteOperationDisable( cmd ) {
            try {
                await this.$confirm(`此操作将禁用 ${cmd.site} 站点, 是否继续?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                });
            } catch {
                return;
            }

            let vhost = this.list[cmd.index];
            let server = this.$store.getters.serverCurrent;
            await server.exec(`a2dissite ${vhost.file}`);
            await server.exec('systemctl restart apache2');
            await this.actionRefresh();
        },
    }
}
</script>